package api

import (
	"encoding/json"
	"net/url"
	"strconv"
	"strings"

	"github.com/valyala/fasthttp"
	"permission/api/param_type"
	"permission/config/error_code"
	"permission/databases"
	"permission/user_info"
	"permission/vigo_loger"
)

// 获取会话信息
func (bs *BaseServer) GetSession(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	userId, _ :=strconv.Atoi(strings.Trim(string(qArgs.Peek("UserId")), " "))
	appId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("appId")), " "))
	if userId==0 || appId == 0 {
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	data, err, status := user_info.GetSession(int32(userId), int32(appId))
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = status
		res.Info = error_code.INFO[status]
	} else {
		res.Result = data
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
}

// 获取所有用户信息
func (bs *BaseServer) GetAllUser(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	res.Status = error_code.SUCCESS_STATUS
	res.Info = error_code.INFO[error_code.SUCCESS_STATUS]
	resApi := param_type.ApiUserListResponse{}
	users, err := user_info.GetUserByDB()
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.NOT_FIND_ERR
		res.Info = error_code.INFO[error_code.NOT_FIND_ERR]
	} else {
		resApi.TpoSysUsers = users
		res.Result = resApi
	}

	response, _ := json.Marshal(res)
	ctx.Write(response)
}

// 检查用户是否登陆
func (bs *BaseServer) CheckLogin(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	qArgs := ctx.QueryArgs()
	userId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("UserId")), " "))
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	res.Status = error_code.NOT_FIND_ERR
	res.Info = error_code.INFO[error_code.NOT_FIND_ERR]

	if string(userId) == "" {
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	// redis get data
	cache := user_info.NewVigoCache()
	defer cache.Close()
	val := cache.CheckLogin(int32(userId))

	if val != nil {
		res.Status = error_code.SUCCESS_STATUS
		res.Info = error_code.INFO[error_code.SUCCESS_STATUS]
	}

	response, _ := json.Marshal(res)
	ctx.Write(response)
}

func (bs *BaseServer) ERPLogin(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}

	postValues := ctx.PostArgs()
	account := strings.Trim(string(postValues.Peek("erpguid")), " ")
	appId, _ := strconv.Atoi(strings.Trim(string(postValues.Peek("appId")), " "))
	gdSid, _ := url.QueryUnescape(strings.Trim(string(postValues.Peek("GDSID")), " "))
	if account == "" || appId == 0 || gdSid == "" {
		status := error_code.Code_type_int(error_code.PARAM_ERR)
		res.Status = status
		res.Info = error_code.INFO[status]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	data, err, status := user_info.ERPLogin(account, int32(appId), string(gdSid))
	if err != nil {
		res.Status = status
		res.Info = error_code.INFO[status]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	// 登陆日志
	var loginSut databases.Tpo_Sys_Users_Login
	loginSut.App_id = int32(appId)
	loginSut.User_id = data.UserID
	loginSut.Login_ip = string(ctx.Request.Header.PeekBytes([]byte("X-Real-Ip")))
	go user_info.LoginWriteLog(loginSut)

	res.Result = data
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 登陆
func (bs *BaseServer) Login(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}

	postValues := ctx.PostArgs()
	account := strings.Trim(string(postValues.Peek("account")), " ")
	password := strings.Trim(string(postValues.Peek("password")), " ")
	//appId, _ := strconv.Atoi(strings.Trim(string(postValues.Peek("appId")), " "))
	//gdSid, _ := url.QueryUnescape(strings.Trim(string(postValues.Peek("GDSID")), " "))
	data, err, status := user_info.Login(account, password, 0)
	if err != nil {
		res.Status = status
		res.Info = error_code.INFO[status]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	// 登陆日志
	var loginSut databases.Tpo_Sys_Users_Login
	loginSut.App_id = 0//int32(appId)
	loginSut.User_id = data.UserID
	loginSut.Login_ip = string(ctx.Request.Header.PeekBytes([]byte("X-Real-Ip")))
	go user_info.LoginWriteLog(loginSut)

	res.Result = data
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 修改密码
func (bs *BaseServer) ChangePwd(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}

	postValues := ctx.PostArgs()
	account := strings.Trim(string(postValues.Peek("account")), " ")
	oldPassword := strings.Trim(string(postValues.Peek("oldPassword")), " ")
	newPassword := strings.Trim(string(postValues.Peek("newPassword")), " ")
	if oldPassword == newPassword {
		res.Status = error_code.PASSWORD_SAME
		res.Info = error_code.INFO[error_code.PASSWORD_SAME]
	} else {
		err, status := user_info.ChangePwd(account, oldPassword, newPassword)
		if err != nil {
			vigo_loger.AddGrayLog(err.Error())
			res.Status = status
			res.Info = error_code.INFO[status]
		}
	}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// EditUser 编辑用户信息，密码除外
func (bs *BaseServer) EditUser(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	var editUserInfo struct {
		OperatorId int
		Source     string
		Data       databases.Tpo_Sys_Users
	}

	json.Unmarshal(ctx.PostBody(), &editUserInfo)
	if editUserInfo.Data.UserID == 0 {
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
		vigo_loger.AddGrayLog("EditUser", map[string]interface{}{"Error": "参数错误", "Body": string(ctx.PostBody())})
	} else {
		data := editUserInfo.Data
		if valid, err := user_info.IsValidUserInfo(editUserInfo.Data.UserID, &data); err != nil {
			res.Status = error_code.SYS_ERR
			res.Info = error_code.INFO[error_code.SYS_ERR]
			vigo_loger.AddGrayLog("EditUser", map[string]interface{}{"Error": err.Error()})
		} else if !valid {
			res.Status = error_code.PARTIALPHONE_SAME
			res.Info = error_code.INFO[error_code.PARTIALPHONE_SAME]
			vigo_loger.AddGrayLog("EditUser", map[string]interface{}{"Error": res.Info})
		} else {
			if err = user_info.EditUserByUserId(editUserInfo.Data.UserID, &data); err != nil {
				res.Status = error_code.SYS_ERR
				res.Info = error_code.INFO[error_code.SYS_ERR]
				vigo_loger.AddGrayLog("EditUser", map[string]interface{}{"Error": err.Error()})
			} else {
				vf := databases.NewLogInfoFactory()
				vf.Table.Operation = string(ctx.Path())
				vf.Table.OperatorID = int64(editUserInfo.OperatorId)
				vf.Table.Source = editUserInfo.Source
				vf.Table.Result = error_code.INFO[error_code.SUCCESS_STATUS]
				b, _ := json.Marshal(&editUserInfo.Data)
				vf.Table.Remark = "修改内容:" + string(b)
				vf.AddNewLog()
				res.Status = error_code.SUCCESS_STATUS
				res.Info = error_code.INFO[error_code.SUCCESS_STATUS]
			}
		}
	}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 退出
func (bs *BaseServer) Destroy(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	userId, _ := url.QueryUnescape(strings.Trim(string(ctx.FormValue("userId")), " "))
	cache := user_info.NewVigoCache()
	defer cache.Close()
	ok, _ := cache.DestroyUser(userId)
	if !ok {
		res.Status = error_code.REDIS_ERR
		res.Info = error_code.INFO[error_code.REDIS_ERR]
	}
	//go user_info.LoginOutApi(userId)
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 获取部门节点
func (bs *BaseServer) GetDepartmentNode(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	userId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("userId")), " "))
	data, err := user_info.GetDepartNode(int64(userId))

	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	} else {
		res.Result = data
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 获取部门节点 所有用户信息
func (bs *BaseServer) GetAllDepartmentNode(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	userId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("userId")), " "))
	data, err := user_info.GetDepartNodeAllUser(int64(userId))

	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	} else {
		res.Result = data
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

func (bs *BaseServer) GetDepartByLevel(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	campusLevel, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("campus_level")), " "))
	err, data := user_info.GetDepartInfoByLevel(int32(campusLevel))

	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.DB_ERR
		res.Info = error_code.INFO[error_code.DB_ERR]
	} else {
		res.Result = data
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

func (bs *BaseServer) GetUsersByWorkNo(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	userData := param_type.ApiUserListResponse{}
	qArgs := ctx.QueryArgs()
	workStr := strings.Trim(string(qArgs.Peek("workIds")), " ")
	workIds := strings.Split(workStr, ",")
	if len(workIds) >= 1000 {
		res.Status = error_code.USER_NUM_ERR
		res.Info = error_code.INFO[error_code.USER_NUM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}

	data, err := user_info.GetUserByWorkIds(workIds...)

	if err != nil {
		res.Status = error_code.NOT_FIND_ERR
		res.Info = error_code.INFO[error_code.NOT_FIND_ERR]
	} else {
		userData.TpoSysUsers = data
		res.Result = userData
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)

}

func (bs *BaseServer) GetUsersByMobile(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	userData := param_type.ApiUserListResponse{}
	qArgs := ctx.PostArgs()
	mobileStr := strings.TrimSpace(string(qArgs.Peek("mobile")))
	mobiles := strings.Split(mobileStr, ",")
	if len(mobiles) > 1000 || len(mobiles) == 0 || mobiles[0] == "" {
		res.Status = error_code.USER_NUM_ERR
		res.Info = error_code.INFO[error_code.USER_NUM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}

	var err error
	userData.TpoSysUsers, err = user_info.GetUserByMobiles(mobiles...)
	if err != nil {
		res.Status = error_code.SYS_ERR
		res.Info = err.Error()
	} else {
		res.Status = error_code.SUCCESS_STATUS
		res.Info = error_code.INFO[error_code.SUCCESS_STATUS]
		res.Result = userData
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
}

// 根据座机号获取用户
func (bs *BaseServer) GetUsersByAgent(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	userData := param_type.ApiUserListResponse{}
	qArgs := ctx.PostArgs()
	agentByte := qArgs.PeekMulti("agentIds[]")
	if len(agentByte) >= 1000 {
		res.Status = error_code.USER_NUM_ERR
		res.Info = error_code.INFO[error_code.USER_NUM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	var agentIds []string
	for _, agentId := range agentByte {
		agentIds = append(agentIds, string(agentId))
	}

	data, err := user_info.GetUserByAgents(agentIds...)
	if err != nil {
		res.Status = error_code.NOT_FIND_ERR
		res.Info = error_code.INFO[error_code.NOT_FIND_ERR]
	} else {
		userData.TpoSysUsers = data
		res.Result = userData
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
}

//
func (bs *BaseServer) GetUserByPartial(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	userData := param_type.ApiUserListResponse{}
	qArgs := ctx.PostArgs()
	partialByte := qArgs.PeekMulti("partialIds[]")
	if len(partialByte) >= 1000 {
		res.Status = error_code.USER_NUM_ERR
		res.Info = error_code.INFO[error_code.USER_NUM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	var partialIds []string
	for _, partialId := range partialByte {
		partialIds = append(partialIds, string(partialId))
	}

	data, err := user_info.GetUserByPartial(partialIds...)
	if err != nil {
		res.Status = error_code.NOT_FIND_ERR
		res.Info = error_code.INFO[error_code.NOT_FIND_ERR]
	} else {
		userData.TpoSysUsers = data
		res.Result = userData
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)

}

func (bs *BaseServer) GetUserByTrAgentNo(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	userData := param_type.ApiUserListResponse{}
	qArgs := ctx.PostArgs()
	partialByte := qArgs.PeekMulti("trAgentNos[]")
	if len(partialByte) >= 1000 {
		res.Status = error_code.USER_NUM_ERR
		res.Info = error_code.INFO[error_code.USER_NUM_ERR]
		response, _ := json.Marshal(res)
		ctx.Write(response)
		return
	}
	var partialIds []string
	for _, partialId := range partialByte {
		partialIds = append(partialIds, string(partialId))
	}

	data, err := user_info.GetUserByTrAgentNo(partialIds...)
	if err != nil {
		res.Status = error_code.NOT_FIND_ERR
		res.Info = error_code.INFO[error_code.NOT_FIND_ERR]
	} else {
		userData.TpoSysUsers = data
		res.Result = userData
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)

}

// 修改用户基本信息
func (bs *BaseServer) EditUserById(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.PostArgs()
	userId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("user_id")), " "))
	trueName := strings.Trim(string(qArgs.Peek("true_name")), " ")
	nickname := strings.Trim(string(qArgs.Peek("nickname")), " ")
	qq := strings.Trim(string(qArgs.Peek("qq")), " ")
	homeTel := strings.Trim(string(qArgs.Peek("home_tel")), " ")
	homeAddr := strings.Trim(string(qArgs.Peek("home_addr")), " ")
	avatar := strings.Trim(string(qArgs.Peek("avatar")), " ")
	weChatNumber := strings.Trim(string(qArgs.Peek("wechat_number")), " ")
	weChatImgUrl := strings.Trim(string(qArgs.Peek("wechat_img_url")), " ")
	data := databases.Tpo_Sys_Users{}
	data.TrueName = trueName
	data.Ename = nickname
	data.HomeAddr = homeAddr
	data.HomeTel = homeTel
	data.WeChat = weChatNumber
	data.WeChatImgUrl = weChatImgUrl
	data.UserID = int64(userId)
	data.Qq = qq
	data.Avatar = avatar
	err := user_info.EditUserByUserId(int64(userId), &data)
	if err != nil {
		res.Status = error_code.REDIS_ERR
		res.Info = error_code.INFO[error_code.REDIS_ERR]
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// GetUserByErp 根据erpuserid获取用户
func (bs *BaseServer) GetUserByErp(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	var userData param_type.ApiUserListResponse
	// post
	var erpIdsList []string
	qArgs := ctx.PostArgs()
	erpIdsStr := string(qArgs.Peek("erpIds"))
	if erpIdsStr == "" {
		userIdsByte := qArgs.PeekMulti("erpIds[]")
		if len(userIdsByte) >= 1000 {
			res.Status = error_code.USER_NUM_ERR
			res.Info = error_code.INFO[error_code.USER_NUM_ERR]
			response, _ := json.Marshal(res)
			ctx.Write(response)
			return
		}
		for _, erpIdByte := range userIdsByte {
			erpIdsList = append(erpIdsList, string(erpIdByte))
		}
	} else {
		erpIdsList = append(erpIdsList, erpIdsStr)
	}

	data, err := user_info.GetUserInfoByErp(erpIdsList...)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	}
	var ids []int64
	for _, d := range data {
		ids = append(ids, d.UserID)
	}
	urs, err := user_info.GetUserRoleByIds(ids...)
	for i, d := range data {
		for _, u := range urs {
			if u.UserId == d.UserID {
				d.UserRole = append(d.UserRole, u)
			}
		}
		data[i] = d
	}
	userData.TpoSysUsers = data
	res.Result = userData
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 获取 leader
func (bs *BaseServer) GetLeader(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)
	qArgs := ctx.QueryArgs()
	userId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("userId")), " "))
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	data, err := user_info.GetLeaderTree(int64(userId))
	var resLeader param_type.ApiLeaderResponse
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	} else {
		resLeader.Leader = data
		res.Result = resLeader
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return

}

// 获取部门：根据部门 ID
func (bs *BaseServer) GetDepartNodeByDepartId(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	resNode := param_type.ApiDepartmentResponse{}
	qArgs := ctx.QueryArgs()
	departId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("departId")), " "))
	data, err := user_info.GetDepartNodeByDepartId(int64(departId))
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	} else {
		resNode.Tpo_Sys_Departments = data
		res.Result = resNode
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

func (bs *BaseServer) GetAppNavigationNode(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	qArgs := ctx.QueryArgs()
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	appId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("appId")), " "))
	data, err := user_info.GetAppNavigation(int32(appId))
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	} else {
		r := param_type.ApiAppNavigationRes{}
		r.TpoSysNavigations = data
		res.Result = r
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 根据角色获取部门和用户
func (bs *BaseServer) GetRoleDepartUser(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	qArgs := ctx.QueryArgs()
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	roleId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("roleId")), " "))
	data, err, status := user_info.GetDepartUserByRole(int64(roleId))
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = status
		res.Info = error_code.INFO[status]
	} else {
		res.Result = data
	}
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 用户信息
func (bs *BaseServer) GetUserInfo(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	var userData param_type.ApiUserListResponse
	// post
	var userIdsList []int64
	qArgs := ctx.PostArgs()
	userIdsStr := string(qArgs.Peek("userIds"))
	if userIdsStr == "" {
		userIdsByte := qArgs.PeekMulti("userIds[]")
		if len(userIdsByte) >= 1000 {
			res.Status = error_code.USER_NUM_ERR
			res.Info = error_code.INFO[error_code.USER_NUM_ERR]
			response, _ := json.Marshal(res)
			ctx.Write(response)
			return

		}
		for _, userIdByte := range userIdsByte {
			userIdInt, _ := strconv.Atoi(string(userIdByte))
			userIdsList = append(userIdsList, int64(userIdInt))
		}
	} else {
		userIdInt, _ := strconv.Atoi(userIdsStr)
		userIdsList = append(userIdsList, int64(userIdInt))
	}
	data, err := user_info.GetUserByIds(userIdsList...)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	}
	userData.TpoSysUsers = data
	res.Result = userData
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 用户信息
func (bs *BaseServer) FindAliMQ(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.PostArgs()
	userIdsStr := strings.Trim(string(qArgs.Peek("userIds")), " ")
	userIds := strings.Split(userIdsStr, ",")
	userIdsInt := []int64{}
	for _, val := range userIds {
		i, _ := strconv.Atoi(val)
		userIdsInt = append(userIdsInt, int64(i))
	}
	data, err := user_info.FindUserAliMQ(userIdsInt)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.DB_ERR
		res.Info = error_code.INFO[error_code.DB_ERR]
	}
	res.Result = struct {
		Tpo_Sys_User_AliyunMq interface{}
	}{data}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// func ids ��询信�� (部���树)
func (bs *BaseServer) FindDepartByFuncId(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	funcKey := strings.Trim(string(qArgs.Peek("func_key")), " ")
	appId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("app_id")), " "))
	data, err := user_info.FindDepartByFuncIDs(int32(appId), funcKey)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	}
	res.Result = struct {
		Tpo_Sys_User_Func interface{}
	}{data}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 获取角色列表
func (bs *BaseServer) FindRoles(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	data, err := user_info.FindRoles()
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.DB_ERR
		res.Info = error_code.INFO[error_code.DB_ERR]
	}
	res.Result = struct {
		Tpo_Sys_Roles interface{}
	}{data}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// campus id 部门 ids
func (bs *BaseServer) FindDepartByCampus(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	campusType, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("campus_level_type")), " "))
	campusId, _ := strconv.Atoi(strings.Trim(string(qArgs.Peek("campus_id")), " "))
	data, err := user_info.FindDepartByCampus(int32(campusId), int32(campusType))
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = error_code.PARAM_ERR
		res.Info = error_code.INFO[error_code.PARAM_ERR]
	}
	res.Result = struct {
		Tpo_Department_Ids interface{}
	}{data}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

func (bs *BaseServer) FindPermission(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.QueryArgs()
	userId, _ := json.Number(strings.Trim(string(qArgs.Peek("user_id")), " ")).Int64()
	data, err, status := user_info.FindPermission(userId)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = status
		res.Info = error_code.INFO[status]
	}
	res.Result = data

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 重置密码
func (bs *BaseServer) ResetPassword(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}

	postValues := ctx.PostArgs()
	account := strings.Trim(string(postValues.Peek("account")), " ")
	password := strings.Trim(string(postValues.Peek("password")), " ")

	err, status := user_info.ResetPassword(account, password)
	if err != nil {
		vigo_loger.AddGrayLog(err.Error())
		res.Status = status
		res.Info = error_code.INFO[status]
	}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}
func (bs *BaseServer) EdsAddUser(ctx *fasthttp.RequestCtx) {
	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	qArgs := ctx.PostArgs()
	userData := databases.Tpo_Sys_Users{}
	userData.UserName = string(qArgs.Peek("UserName"))
	userData.TrueName = string(qArgs.Peek("TrueName"))
	sex, _ := strconv.Atoi(string(qArgs.Peek("Sex")))
	userData.Sex = int32(sex)
	userData.OfficeAddr = string(qArgs.Peek("OfficeAddr"))
	isdelete, _ := strconv.Atoi(string(qArgs.Peek("IsDelete")))
	userData.IsDelete = int32(isdelete)
	//userData.ErpCreateBy = string(qArgs.Peek("ErpCreateBy"))
	userData.PartialPhone = string(qArgs.Peek("PartialPhone"))
	////userData.ErpUserId = string(qArgs.Peek("ErpUserId"))
	//userData.ErpDepartmentId = string(qArgs.Peek("ErpDepartmentId"))

	//if userData.ErpDepartmentId == "" || userData.ErpUserId == "" {
	//	res.Status = error_code.PARAM_ERR
	//	res.Info = error_code.INFO[error_code.PARAM_ERR]
	//}

	//err, status := user_info.EdsAddUser(&userData, userData.ErpDepartmentId)
	//if err != nil {
	//	res.Status = status
	//	res.Info = error_code.INFO[status]
	//}

	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}

// 根据条件获取用户信息
func (bs *BaseServer) GetUserByCondition(ctx *fasthttp.RequestCtx) {
	bs.construct(ctx)

	res := ApiBaseResponse{HttpCode: ctx.Response.StatusCode()}
	// post
	qArgs := ctx.PostArgs()
	userIdsInt    := string(qArgs.Peek("userIds"))		//用户id
	mainroleInt   := string(qArgs.Peek("mainrole"))		//用户身份
	TrueNameStr   := string(qArgs.Peek("trueName"))		//用户姓名
	deparentIdInt := string(qArgs.Peek("deparentid"))	//部门id
	offsetInt 	  := string(qArgs.Peek("offset"))		//偏移量
	limitInt 	  := string(qArgs.Peek("limit"))		//限制条数

	data := user_info.GetUserByCondition(userIdsInt, mainroleInt, TrueNameStr, deparentIdInt, offsetInt, limitInt)
	res.Result = data
	response, _ := json.Marshal(res)
	ctx.Write(response)
	return
}
